<template>
	<div class="switch-com flex flex-wrap items-center justify-center relative">
		<div
			class="switch-item w-fit text-center text-gray-500 flex items-center justify-center"
			v-for="(item, index) in items"
			:key="item.value">
			<icon
				:size="14"
				class="mr-1"
				:name="item.icon"
				v-show="item.icon"
				:style="{ color: item.iconColor }" />
			<span
				@click.stop="switchItem($event, index)"
				class="text-sm cursor-pointer"
				:class="currentActive === index ? 'font-bold text-blue-500' : ''">
				{{ item.name }}
			</span>
		</div>
		<div
			class="under-line absolute bottom-[-3px] ease-in-out"
			:style="{ left: `${underLineLeft}px` }">
			<div class="h-1 bg-blue-500 rounded-full" :style="{ width: `${underLineWidth}px` }"></div>
		</div>
	</div>
</template>

<script lang="ts">
export interface SwitchItem {
	icon?: string;
	name: string;
	value: any;
	iconColor?: string;
}

export default defineComponent({
	name: 'SwitchCom',
	props: {
		// 选项数组
		items: {
			type: Array as PropType<SwitchItem[]>,
			required: true,
		},
		defaultActive: {
			type: Number,
			default: 0,
		},
	},
	emits: ['onActiveChange'],
	setup(props, { emit }) {
		const currentActive = ref<number>(0);
		watch(currentActive, (val: number) => {
			emit('onActiveChange', {
				index: val,
				value: props.items[val].value,
			});
		});

		// 下划线左侧偏移量/宽度
		const underLineLeft = ref<number>(10);
		const underLineWidth = ref<number>(0);

		// 切换选项
		const switchItem = (e: MouseEvent, index: number): void => {
			if (index === currentActive.value) return;
			const target = e.target as HTMLElement;
			underLineLeft.value = target.offsetLeft;
			underLineWidth.value = target.clientWidth;
			currentActive.value = index;
		};

		onMounted(() => {
			// 设置默认激活项
			currentActive.value = props.defaultActive;
			// 设置下划线初始位置
			const target = document.querySelector(
				`.switch-item:nth-child(${props.defaultActive + 1})`
			) as HTMLElement;
			const span = target.childNodes[1] as HTMLElement;
			underLineLeft.value = span.offsetLeft;
			underLineWidth.value = span.offsetWidth;
		});

		return {
			currentActive,
			underLineLeft,
			underLineWidth,
			switchItem,
		};
	},
});
</script>

<style lang="scss" scoped>
.switch-item {
	margin: 0 10px;
}
</style>
